package com.example.jdimust.login;

import androidx.appcompat.app.AlertDialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import android.app.Activity;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

//第二次添加👇
import android.os.Handler;
import android.os.Message;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.jdimust.util.ACache;
import com.example.jdimust.main.MainActivity;
import com.example.jdimust.R;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.List;

import okhttp3.MediaType;

import static android.content.ContentValues.TAG;
//import java.


public class LoginActivity extends Activity implements View.OnClickListener {
    private Button btnGetTitles = null;
    private ListView lvShow = null;
    private List<Object> titleList = null;
    private EditText et_username;
    private EditText et_password;
    private ImageView imgview;
    static String popup_title;
    static String popup_Message;
    static String popup_button;
    private ACache acache;//缓存框架


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        int[] ck = new int[]{};
        ck = screenSize();
        imgview = (ImageView) findViewById(R.id.img_logo);
        setViewSize(imgview, ck);
//        imgview.setWidth(ck[0]);
//        imgview.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        et_username = (EditText) findViewById(R.id.in_user);
        et_password = (EditText) findViewById(R.id.in_pawd);
        initUI();

        btnGetTitles.setOnClickListener(this);

        acache = ACache.get(this);//创建ACache组件


    }


    private void initUI() {
        btnGetTitles = (Button) findViewById(R.id.bt_login);
    }


    @Override
    public void onClick(View arg0) {


        if (!isConnectIsNomarl()){
            Toast.makeText(LoginActivity.this, "请检查网络连接情况！", Toast.LENGTH_SHORT).show();
//            finish();
        }

        new Thread(new GetTitlesThread()).start();
    }

    Handler getTitlesHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            if (msg.what == 100) {
                ArrayAdapter<Object> adapter = new ArrayAdapter<Object>(
                        LoginActivity.this,
                        android.R.layout.simple_list_item_1,
                        titleList);
//                lvShow.setAdapter(adapter);
            }
        }
    };

    class GetTitlesThread implements Runnable {
        @Override
        public void run() {
//            new Thread() {
            String user = et_username.getText().toString();
            String pawd = et_password.getText().toString();
//            String url="https://hzy.graduationproject.xyz/imust-gateway/GetMessage";
            if (user.length() == 0 || pawd.length() == 0) {
                Looper.prepare();
                Toast.makeText(LoginActivity.this, "请输入有效信息！\n账号或密码不能为空！", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
            String login_url = "https://hzy.graduationproject.xyz/Login";
            String json = "{\n" +
                    " \"user\":" + "\"" + user + "\"" + ",\n" +
                    " \"pass\":" + "\"" + pawd + "\"" + "\n" +
                    "}";
            MediaType toheader = MediaType.parse("application/json;charset=utf-8");
//            post方法
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(login_url);
            StringEntity postingString = null;// json传递
            try {
                postingString = new StringEntity(json);
                post.setEntity(postingString);
                post.setHeader("Content-type", "application/json");
                HttpResponse response = httpClient.execute(post);

//                String content0 = NetworkRequest.postaccount("login",json,toheader);

//                response.set
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(response.getStatusLine().getStatusCode());
//                Log.i("test", content);
//                String result = content;
                JSONObject login_json = new JSONObject(content);
                Log.d(TAG, content);
//                System.out.println(login_json);
//                System.out.println(getType(jsonObj));
                String flag = login_json.getString("flag");
                String statumes = login_json.getString("message");
                JSONObject ressult_json = login_json.getJSONObject("result");
                String result = ressult_json.toString();
                JSONObject loginjsonresult = new JSONObject(result);
                String name = loginjsonresult.getString("name");
                String user111 = loginjsonresult.getString("user");
                String userid = loginjsonresult.getString("id");
                String directOperation = loginjsonresult.getString("directOperation");
                String contractOperation = loginjsonresult.getString("contractOperation");
                String configureRoles = loginjsonresult.getString("configureRoles");
                String authorizeUserRoles = loginjsonresult.getString("authorizeUserRoles");
                String setConsensus = loginjsonresult.getString("setConsensus");
                String setCrypto = loginjsonresult.getString("setCrypto");
                String approveTx = loginjsonresult.getString("approveTx");
                String consensusTx = loginjsonresult.getString("consensusTx");
                String registerParticipant = loginjsonresult.getString("registerParticipant");
                String setUserAttributes = loginjsonresult.getString("setUserAttributes");
                String registerUser = loginjsonresult.getString("registerUser");
                String registerEventAccount = loginjsonresult.getString("registerEventAccount");
                String writeEventAccount = loginjsonresult.getString("writeEventAccount");
                String registerDataAccount = loginjsonresult.getString("registerDataAccount");
                String writeDataAccount = loginjsonresult.getString("writeDataAccount");
                String registerContract = loginjsonresult.getString("registerContract");
                String upgradeContract = loginjsonresult.getString("upgradeContract");
                acache.put("acaname", name);
                acache.put("acauser111", user111);
                acache.put("acauserid", userid);
                acache.put("acadirectOperation", directOperation);
                acache.put("acacontractOperation", contractOperation);
                acache.put("acaconfigureRoles", configureRoles);
                acache.put("acaauthorizeUserRoles", authorizeUserRoles);
                acache.put("acaetConsensus", setConsensus);
                acache.put("acasetCrypto", setCrypto);
                acache.put("acaapproveTx", approveTx);
                acache.put("acaconsensusTx", consensusTx);
                acache.put("acaregisterParticipant", registerParticipant);
                acache.put("acasetUserAttributes", setUserAttributes);
                acache.put("acaregisterUser", registerUser);
                acache.put("acaregisterEventAccount", registerEventAccount);
                acache.put("acawriteEventAccount", writeEventAccount);
                acache.put("acaregisterDataAccount", registerDataAccount);
                acache.put("acawriteDataAccount", writeDataAccount);
                acache.put("acaregisterContract", registerContract);
                acache.put("acaupgradeContract", upgradeContract);
                Looper.prepare();
//                showPopup(popup_title="提示", popup_Message="当前登录用户："+name, popup_button="确认");
                Toast.makeText(LoginActivity.this, statumes, Toast.LENGTH_SHORT).show();

                if (flag == "true") {
                    System.out.println("跳转页面");
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);//从SpendingActivity页面跳转至ExpenseProcesActivity页面
//                    startActivity(intent);
                    intent.putExtra("login_reslust", result);//参数：name、value
                    startActivity(intent);
                    //关闭当前界面
                    finish();
                    Looper.loop();
                }
//                System.out.println(name);
            } catch (
                    UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (
                    ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (
                    JSONException e) {
//                e.printStackTrace();
                Looper.prepare();
//                showPopup(popup_title = "提示", popup_Message = "账号或密码错误！\n请检查账号或密码", popup_button = "返回");
                Toast.makeText(LoginActivity.this, "账号或密码错误！\n请检查账号或密码", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
//            }.start();
        }
    }

    private static String getType(Object a) {
        return a.getClass().toString();
    }

    /**
     * 设置弹窗
     *
     * @param show_title   标题
     * @param show_message 弹窗信息
     * @param show_button  返回格式
     */

    public void showPopup(String show_title, String show_message, String show_button) {
        new AlertDialog.Builder(this)
                .setTitle(show_title)
                .setMessage(show_message)
                .setPositiveButton(show_button, null)
                .show();
    }

    //获取屏幕尺寸
    public int[] screenSize() {
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        System.out.println(width + "\n" + height);
        int[] h_w = new int[]{height, width};
        return h_w;
    }


    /**
     * 设置控件大小
     *
     * @param view   控件
     * @param cksize 尺寸
     */
    public static void setViewSize(View view, int[] cksize) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        int set_size = (int) (cksize[1] * 0.6);
        params.width = set_size;
        params.height = set_size;
        view.setLayoutParams(params);
    }

    /** 判断网络是否连接 */
    private boolean isConnectIsNomarl() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String intentName = info.getTypeName();
//            Log.i("通了没！", "当前网络名称：" + intentName);
            return true;
        } else {
//            Log.i("通了没！", "没有可用网络");
            return false;
        }
    }
}

